import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-09-26
 * Time:20:52
 */
public class MySemphore {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        //构造的时候需要指定初始值,计数器的初始值,表示有几个可用资源
        Semaphore semaphore = new Semaphore(1);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    //这是P操作,申请资源,计数器-1
                    semaphore.acquire();
                    for (int i = 0; i < 5_000; i++) {
                        count++;
                    }
                    //这是V操作,释放资源,计数器+1
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);


    }
}
